/*
 * testFramework.c
 *
 * Created: 2015-01-06 12:08:24
 *  Author: Andreas Domfors
 */ 

#include <stdlib.h>
#include <string.h>
#include "drivers/usart.h"
#include "API/rosa.h"
#include "ee_printf.h"
#include "kernel/rosa_queues.h"
#include "kernel/rosa_scheduler.h"
#include "kernel/rosa_tim.h"
#include "testFramework.h"

void IdleTaskFunc(void);

int taskResults[5];
int totalNumberOfTestCases, successfulTests, failedTests;

#define IDLE_STACK_SIZE 0x100
void resetTest(void)
{
	ROSA_freeAllResources();
	memset(taskResults, 0, sizeof(taskResults));
	
	ROSA_taskCreate("idle", IdleTaskFunc, 0, IDLE_STACK_SIZE);
}

// Returns stack usage
static int reportStackUsage(tcb *task)
{
	int stackUsage = getMaximumStackUsage(task);
	int percent = (100 * stackUsage) / task->datasize;
	ee_printf("Task: %.4s Stack: %d / %d (%d %%)\n", task->id, stackUsage, task->datasize, percent);
	return stackUsage;
}

static int reportQueueStackUsage(tcb *queueHead)
{
	int sum = 0;
	for(tcb *i = queueHead; i != NULL; i = i->nexttcb)
	{
		sum += reportStackUsage(i);
	}
	return sum;
}

void reportAllStackUsage(void)
{
	int usedMemory = 0;
	usedMemory += reportQueueStackUsage(readyQueueHead);
	usedMemory += reportQueueStackUsage(waitingQueueHead);
	usedMemory += reportQueueStackUsage(blockedQueueHead);
	usedMemory += reportQueueStackUsage(deleteQueue);
	
	int memorySize = 64*1024;
	ee_printf("Total memory usage for stacks: %d / %d (%d %%)\n", usedMemory, memorySize, (usedMemory * 100)/memorySize);
	ee_printf("Time used for 128 systick interrupts: %d\n", getTotalSystickTime());
}

void schedulerStopper(void)
{
	ROSA_taskDelay(150);
	ROSA_stopScheduler();
}

void performTests(TestEntry *entries, int count)
{
	for(int i=0; i<count; i++)
	{
		ee_printf("Test: %s\n", entries[i].name);
		entries[i].func();
		//reportAllStackUsage();
		resetTest();		
		ee_printf("Test complete\n");
	}	
}
